<template>
  <el-form
    :model="form"
    label-width="auto"
    style="max-width: 600px"
    class="login-form"
  >
    <el-form-item label="用户名">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="form.password" type="password" />
    </el-form-item>
    <el-form-item>
      <div class="flex">
        <el-button type="primary" @click="onSubmit" @keydown.enter="onKeyDown"
          >登陆</el-button
        >
        <el-button type="default">注册</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { onMounted, onUnmounted } from "vue";
import store from "../store/index";

const router = useRouter();
// do not use same name with ref
const form = reactive({
  username: "",
  password: "",
});
const onSubmit = () => {
  axios
    .post("/admin/login", {
      username: form.username,
      password: form.password,
    })
    .then((res) => {
      if (res.code === 200) {
        localStorage.setItem("token", res.data);
        // store.commit("setUserInfo", res.data)
        router.push({
          path: "/index",
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

const onKeyDown = (e) => {
  if (e.keyCode === 13 || e.keyCode === 100) {
    onSubmit();
  }
};

onMounted(() => {
  window.addEventListener("keydown", onKeyDown);
});

onUnmounted(() => {
  //销毁事件
  window.removeEventListener("keydown", onKeyDown, false);
});
</script>

<style lang="scss" scoped>
.login-form {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -80%);
  border: 1px solid #5a9cf8;
  border-radius: 12px;
  padding: 40px;
  width: 400px;
}

.flex {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
